package com.hellloop.pim.alphabeat.gui;
import java.awt.*;
import javax.swing.*;

import com.hellloop.pim.alphabeat.game.PIMClientGame;

public class QuestionPanel extends JPanel{

	private PIMClientGame pimClientGame;
	
	private String question = "Default";
	private int questionWidth;
	private Font font;
	
	private int ansIndex;
	private char answer;
	
	private boolean lockscreen=false;
	
	public QuestionPanel(PIMClientGame pimClientGame){
		this.pimClientGame = pimClientGame;
	}
	
	protected void paintComponent(Graphics g){
		super.paintComponent(g);
	
		if (font != null) g.setFont(font);
		FontMetrics fm = g.getFontMetrics();
		
		// Draw Question
		questionWidth = fm.stringWidth(question);
		int x = (this.getWidth() - questionWidth)/2;
		int y = (this.getHeight())/2;
		
		g.setColor(Color.BLACK);
		g.drawString(question, x, y);
		
			// lock screen so that the program won't repaint when minimize windows
			// please note that we still want it to paint old correct answers (in else)
			if (lockscreen){

				lockscreen = false;				
				
//				System.out.println(question + " " +ansIndex);
				
				// Draw Correct Answers
				g.setColor(Color.GREEN);
				if (question.substring(0, ansIndex + 1) != null)
					g.drawString(question.substring(0, ansIndex + 1), x, y);
			
//				// Draw the Current Answer
//				x = (this.getWidth() - questionWidth)/2;
//				for (int i = 0; i < ansIndex; i++){
//					x += fm.stringWidth(question.substring(i, i+1));
//				}
//				y = (this.getHeight())/2;		
//				g.drawString(answer+"", x, y);
				
				if (question.length() <= ansIndex + 1){
					ansIndex = 0;
					pimClientGame.changeQuestion();
//					isQuestionReady = false;
				} else {
					ansIndex++;
				}
			
			} else {
				// Draw Old Correct Answers
				// use only ansIndex (do not +1) because ansIndex was accumlated from the previous round
				g.setColor(Color.GREEN);
				if (question.substring(0, ansIndex) != null)
					g.drawString(question.substring(0, ansIndex), x, y);
			}

	}
	
	public void writeQuestion(String question){
		this.question = question;
		
		repaint();
	}
	
	public void writeQuestion(String question, Font font){
		this.question = question;
		this.font = font;;
		
		repaint();
	}
	
	public boolean writeAnswer(char answer){
		this.answer = answer;
		if (question.charAt(ansIndex) == answer){
			lockscreen = true;
			repaint();
			return true;
		} else{
			System.err.println("Wrong");
			return false;
		}
	}
	
}
